import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { collection, query, where, getDocs } from 'firebase/firestore';
import { db } from '../services/firebase';
import { Copywriting } from '../types';
import CopywritingCard from '../components/features/CopywritingCard';
import SearchBar from '../components/features/SearchBar';

const Search = () => {
  const [searchParams] = useSearchParams();
  const searchQuery = searchParams.get('q') || '';
  const [copywritings, setCopywritings] = useState<Copywriting[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const searchCopywritings = async () => {
      if (!searchQuery) {
        setLoading(false);
        return;
      }

      try {
        // 这是一个简单的搜索实现，只搜索标题和内容
        // 在实际应用中，你可能需要使用更高级的搜索功能，如 Algolia 或 Elasticsearch
        const q = query(
          collection(db, 'copywriting'),
          where('status', '==', 'published')
        );
        const querySnapshot = await getDocs(q);
        const results = querySnapshot.docs
          .map((doc) => ({
            id: doc.id,
            ...doc.data(),
          }))
          .filter((doc: any) => {
            const searchLower = searchQuery.toLowerCase();
            return (
              doc.title?.toLowerCase().includes(searchLower) ||
              doc.content.toLowerCase().includes(searchLower) ||
              doc.tags.some((tag: string) =>
                tag.toLowerCase().includes(searchLower)
              )
            );
          }) as Copywriting[];

        setCopywritings(results);
      } catch (err) {
        console.error('Error searching copywritings:', err);
        setError('搜索失败');
      } finally {
        setLoading(false);
      }
    };

    searchCopywritings();
  }, [searchQuery]);

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-4">搜索文案</h1>
        <SearchBar />
      </div>

      {loading ? (
        <div className="text-center py-8">
          <div className="text-lg">搜索中...</div>
        </div>
      ) : error ? (
        <div className="text-red-600 text-center">{error}</div>
      ) : (
        <div>
          <div className="text-gray-600 mb-4">
            找到 {copywritings.length} 条相关文案
          </div>
          {copywritings.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              没有找到相关文案
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {copywritings.map((copywriting) => (
                <CopywritingCard key={copywriting.id} copywriting={copywriting} />
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Search;
